#coding: utf-8
from invenio.messages import gettext_set_language

def format_element(bfo):
	"""
	Prints title (subtitle) and translated title (translated subtitle) in compact view
	with Javascript Original / Translated view
	"""
	_ = gettext_set_language(bfo.lang)
	def printTitles(titles):
		if len(titles) == 0:
			return ""
		elif len(titles) == 1:
			return titles[0]
		elif len(titles) == 2:
			return "%s (%s)" % (titles[0], titles[1])
	title = bfo.field("24500a")
	altTitle = bfo.field("24500b")
	titleTrans = bfo.field("24633a")
	altTitleTrans = bfo.field("24633b")
	if not title and not altTtitle and not titleTrans and not altTitleTrans:
		return ""
	orig = [t for t in (title, titleTrans) if t]
	trans = [t for t in (altTitle, altTitleTrans) if t]
	if not trans:
		return printTitles(orig)
	elif not orig:
		return printTitles(trans)
	else:
		res = """<script type="text/javascript">
			 	$(document).ready(function(){
				 	$(".titleLang").live("click", function(){
				 		$(".titleLang").css({"color" : "grey", "cursor" : "pointer"});
				 		$(this).css({"color" : "black", "cursor" : "default"});
				 		var id = $(this).attr("id");
				 		$(".recTitle").css("display", "none");
				 		$("#title" + id).css("display", "inline");
				 		
				 	});
				 });
			 </script>"""
		res += "<span class='titleLang' id='orig' style='cursor:default;'>[{0}]</span> <span class='titleLang' id='trans' style='color:grey;cursor:pointer;'>[{1}]</span><br />".format(_("Original"), _("Translation"))
		res += """<span class="recTitle" id="titleorig">%s</span>
		<span class="recTitle" id="titletrans" style="display:none;">%s</span>
		""" % (printTitles(orig), printTitles(trans))
	return res
